 
//绘制文本
 function drawText({ options, data }) {
  const {
    x,
    y, text, baseLine,
  } = data;
  if (Array.isArray(text)) {
    let preText = { x, y, baseLine }; 
    text.forEach(item => {
      preText.x += item.marginLeft || 0;
      const textWidth = _drawSingleText(Object.assign(item, {
        ...preText,
      }), options);
      preText.x += textWidth + (item.marginRight || 0); // 下一段字的 x 轴为上一段字 x + 上一段字宽度
    })
  } else {
    _drawSingleText(data, options);
  }
}

  function _drawSingleText(data, options) {
  let { x, y, fontSize, color='#000', baseLine, textAlign = 'left', text, opacity = 1, textDecoration = 'none',
      width = 0, lineNum = 1, lineHeight = 0, fontWeight = 'normal', fontStyle = 'normal', fontFamily = "sans-serif" } = data;
    console.log('text',text);
  const { ctx ,pixelRatio} = options;
  ctx.save();
  ctx.beginPath();
  ctx.font = fontStyle + " " + fontWeight + " " + fontSize + "px " + fontFamily
  ctx.globalAlpha = opacity;
  if (typeof text === 'object') {
    text = text.text
  }
  if (color) {ctx.fillStyle = color;}
  if (baseLine) {ctx.textBaseline = baseLine;}
    
  ctx.textAlign = textAlign;
  let textWidth = (ctx.measureText(text).width);
  const textArr  = [];
  let drawWidth = width
  if (width && textWidth > drawWidth) {
    // 文本宽度 大于 渲染宽度
    let fillText = '';
    let line = 1;
    for (let i = 0; i <= (text).length - 1; i++) {  // 将文字转为数组，一行文字一个元素
      fillText = fillText + text[i];
      if ((ctx.measureText(fillText).width) >= drawWidth) {
        if (line === lineNum) {
          if (i !== (text).length - 1) {
            fillText = fillText.substring(0, fillText.length - 1) + '...';
          }
        }
        if (line <= lineNum) {
          textArr.push(fillText);
        }
        fillText = '';
        line++;
      } else {
        if (line <= lineNum) {
          if (i === (text).length - 1) {
            textArr.push(fillText);
          }
        }
      }
    }
    textWidth = width;
  } else {
    textArr.push(text );
  }

  textArr.forEach((item, index) => {
    ctx.fillText(item, x,y + (lineHeight || fontSize) * index);
  })
  ctx.restore();
  // textDecoration
  if (textDecoration !== 'none') {
    let lineY = y;
    if (textDecoration === 'line-through') {
      // 目前只支持贯穿线
      lineY = y;
      // 小程序画布baseLine偏移阈值
      let threshold = 5;

      // 根据baseLine的不同对贯穿线的Y坐标做相应调整
      switch (baseLine) {
        case 'top':
          lineY += fontSize / 2 + threshold;
          break;
        case 'middle':
          break;
        case 'bottom':
          lineY -= fontSize / 2 + threshold;
          break;
        default:
          lineY -= fontSize / 2 - threshold;
          break;
      }
    }
    ctx.save();
    ctx.moveTo(x, lineY);
    ctx.lineTo(x + textWidth,lineY);
    if(color){ctx.strokeStyle = color;} 
    ctx.stroke();
    ctx.restore();
  }
  return textWidth;
}
 
module.exports = drawText
exports._drawSingleText = _drawSingleText